package com.Nuyoah.demo01.controller;

import com.Nuyoah.demo01.DTO.common.PromptReq;
import com.Nuyoah.demo01.service.DeepSeekService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/api")
public class ChatController {

    private final DeepSeekService service;

    public ChatController(DeepSeekService service) {
        this.service = service;
    }

    // 非流式 POST /api/chat
    @PostMapping("/chat")
    public DeferredResult<String> chat(@RequestBody PromptReq req) {
        DeferredResult<String> deferredResult = new DeferredResult<>(300000L); // 5分钟超时

        service.chat(req.prompt())
                .subscribe(
                        deferredResult::setResult,
                        deferredResult::setErrorResult
                );

        return deferredResult;
    }

    // 流式 GET /api/chat/stream?prompt=xxx
    @GetMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public DeferredResult<Flux<String>> chatStream(@RequestParam String prompt) {
        DeferredResult<Flux<String>> deferredResult = new DeferredResult<>(300000L); // 5分钟超时

        try {
            Flux<String> stream = service.chatStream(prompt);
            deferredResult.setResult(stream);
        } catch (Exception e) {
            deferredResult.setErrorResult(e);
        }

        return deferredResult;
    }
}
